<template>
  <!-- 模态登录框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowModel(false)"></div>
    <!-- 登录框 -->
    <div class="login">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowModel(false)"></div>

      <!-- 导航 -->
      <div class="navs">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登录</a
        >
        |
        <a href="#" @click="showQrCode" :class="{ active: !isShowContent }"
          >微信登录</a
        >
      </div>
      <!-- 内容 -->
      <div class="content">
        <!-- 手机号 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input type="text" placeholder="请输入手机号" v-model="phoneNum" />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              :imgs="arr"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            >
            </slide-verify>
          </div>
          <div class="row">
            <input type="text" placeholder="请输入短信验证码" v-model="code" />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="LoginFn">手机号登录</button>
          </div>
        </div>

        <!-- 微信扫码 -->
        <div class="wxLogin" v-show="!isShowContent" id="weixin">微信登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";

// 导入验证码函数
import { testPhoneNum, changeIsShowToast } from "@/utils/index.js";

// 导入请求数据模块
import {
  SendSMSAPI,
  PhoneReginAPI,
  BindingAPI,
  UserProfilesAPI,
} from "@/request/api.js";

export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      arr: [require("../assets/img/integral-01.9386d4bf.png")],
      // 用户输入的手机号
      phoneNum: "",
      count: 5,
      isShowCount: false,
      // 手机验证码
      code: "",
    };
  },

  methods: {
    ...mapMutations({
      changeIsShowModel: "showModal/changeIsShowModel",
      changeIsLogin: "loginStatus/changeIsLogin",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 校验手机号和滑块验证码封装
    toVerify() {
      // 1: 验证手机号  不成功要提示
      // console.log(111);
      if (!testPhoneNum(this.phoneNum)) {
        // alert("请输入正确的手机号码");

        // 调用方法显示提示框
        /*    
        this.changeIsShowToast({
          isShow: true,
          title: "请输入正确的手机号",
          type: "danger",
        }); */

        /*  setTimeout(() => {
          this.changeIsShowToast({
            isShow: false,
          });
        }, 3000); */
        this.asyncIsShowToast({
          isShow: true,
          title: "请输入正确的手机号",
          type: "danger",
        });

        return;
      }
      //2 再试一次  或者  向右滑动
      // 验证滑块验证码
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请重新滑动验证码");
        /*   
        this.changeIsShowToast({
          isShow: true,
          title: "请重新滑动验证码",
          type: "danger",
        });

        setTimeout(() => {
          this.changeIsShowToast({
            isShow: false,
          });
        }, 1000);
        */
        this.asyncIsShowToast({
          isShow: true,
          title: "请重新滑动验证码",
          type: "danger",
        });
        return;
      }

      return true;
    },

    // 获取验证码
    async getCode() {
      // 当前这个方法 验证成功后 才继续后面的操作
      if (!this.toVerify()) return;

      //  3: 发送验证码
      let res = await SendSMSAPI({
        phone: this.phoneNum,
      });

      if (!res) return;

      if (res.code == 0) {
        // 4: 倒计时
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 5;
            this.isShowCount = false;
          }
        }, 1000);
      }

      console.log("res", res);
    },
    // 点击登录
    async LoginFn() {
      // 1: 验证手机号
      // 2: 验证滑块验证码
      // if (!this.toVerify()) return;

      // 3: 验证手机验证码
      if (this.code == "") {
        // alert("请输入手机验证码");
        this.asyncIsShowToast({
          isShow: true,
          title: "请输入手机验证码",
          type: "danger",
        });
        return;
      }

      // 先检查有没有uuid
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindingAPI({
          verifyCode: this.code,
          phone: this.phoneNum,
          uuid: uuid,
        });
      } else {
        //没有uid就正常运行
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNum,
        });
      }

      // 4: 发送登录请求

      if (!res) return;
      console.log("res555555555", res);
      if (res.code == 0) {
        // 1: 提示成功
        alert("登录成功");

        // 2: 存储token (后面请求时使用)
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 3: 关闭登录模态框
        this.changeIsShowModel(false);
        // 4: 更新登录为购物车按钮
        this.changeIsLogin(true);

        // 登录成功后删除uuid
        // 短路运算 uuid存在才执行后面的代码
        uuid && localStorage.removeItem("uuid");

        // 登录成功后删除code
        uuid && this.$router.push(this.$route.path);

        // 获取用户信息
        // let user = await UserProfilesAPI();
        // console.log("user:", user);
        this.asyncChangeUserInfo();

        /*
        后台返回的code为0时，表示登录成功。Topbar.vue
        asyncChangeUserInfo()  === 更新用户信息展示
         */
        //[下一步： 手动删除token，切换导航时，需要还原用户信息]
        /*  
        手动删除token，切换导航时---之前有更新登录状态
        登录状态变化，用户信息也需要变化。

        需要还原用户信息 : 将state中数据，更新回默认的数据 ，
                          修改数据要在mutations里面修改-initUserInfo()。
         */

        //下一步：尝试渲染首页 ， html文件在其他文件夹下。！！
      }
    },

    // 微信扫码登录
    showQrCode() {
      this.isShowContent = false;

      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },
  },
};
</script>
<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .login {
    position: absolute;
    inset: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");

    .close {
      height: 22px;
      background: url("../assets/img/close.png");
      width: 22px;
      position: absolute;
      top: 10px;
      right: 60px;
    }
    .navs {
      display: flex;
      justify-content: center;
      margin-top: 40px;
      a {
        text-decoration: none;
        color: #000;
        padding: 0 10px;
      }
      .active {
        color: red;
      }
    }

    .content {
      width: 355px;
      margin: 20px auto;
      text-align: center;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 25px;
          input {
            flex: 1;
            height: 50px;
            text-indent: 1em;
            outline: none;
          }
        }
        .btn {
          background-color: #0a328e;
          color: #fff;
          border: none;
        }
        .btnlogin {
          width: 100%;
          height: 50px;
        }
        .btncode {
          margin-left: 10px;
          width: 80px;
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>